<template>
	<view>
		<image mode="scaleToFill" v-bind="$attrs" :src="cacheImgUrl"></image>
	</view>
</template>

<script>
	export default {
		// 使用 inheritAttrs: false 选项，避免 attribute 被自动应用到组件根元素上
		inheritAttrs: false,
		props: {
			src: {
				type: String,
				required: true
			},
			name: {
				type: String,
				required: false
			}
		},
		data() {
			return {
				cacheImgUrl: '',
				storageNamePreStr: 'img_cache_'
			};
		},
		methods: {
			removevedFile(filePath) {
				uni.removeSavedFile({
					filePath: filePath,
					fail: (err) => {
						console.error('uni.removeSavedFile ##Fail', err);
					},
					success: (res) => {
						console.log('uni.removeSavedFile ##Success', res);
					}
				});
			},
			getImgLSotage() {
				let cache = undefined;
				if (this.name) {
					let cacheSrcObj = uni.getStorageSync(`${this.storageNamePreStr}${this.name}`);
					//非生产环境才打印！！
					if (process.env.NODE_ENV !== 'production') {
						console.log("图片缓存信息", "name:", this.name, "是否匹配", cacheSrcObj.remoteSrc === this.src, "remoteSrc：",
							cacheSrcObj.remoteSrc, "saveSrc", cacheSrcObj.saveSrc);
					}
					if (cacheSrcObj && this.src && cacheSrcObj.remoteSrc === this.src) {
						cache = cacheSrcObj.saveSrc;
					} else {
						//根据name匹配到远程地址不一样时候，删除本地文件，避免缓存过大
						//不匹配时 ，不要返回缓存图片路径！！，否者外面判断不对
						if (cacheSrcObj && cacheSrcObj.saveSrc) {
							this.removevedFile(cacheSrcObj.saveSrc);
							//清除storage数据
							this.setStorageSync({})
						}
					}
				} else {
					let cacheSrcObj = uni.getStorageSync(this.src);
					if (cacheSrcObj && cacheSrcObj.saveSrc) {
						cache = cacheSrcObj.saveSrc;
					}
				}
				return cache;
			},
			async getCacheImage() {
				try {
					const cache = this.getImgLSotage();
					if (cache) {
						this.cacheImgUrl = cache;
						return;
					}
				} catch (error) {
					console.error('Error getting cache:', error);
				}
			},
			//更新本地缓存
			setStorageSync(value) {
				if (this.name) {
					uni.setStorageSync(`${this.storageNamePreStr}${this.name}`, value);
				} else {
					uni.setStorageSync(this.src, value);
				}
			},
			async downloadAndCacheImage() {
				try {
					const downloadRes = await uni.downloadFile({
						url: this.src
					});
					if (downloadRes.statusCode === 200) {
						const saveRes = await uni.saveFile({
							tempFilePath: downloadRes.tempFilePath
						});
						if (saveRes.savedFilePath) {
							const imgObj = {
								remoteSrc: this.src,
								saveSrc: saveRes.savedFilePath
							};
							//缓存路径信息
							this.setStorageSync(imgObj)
							console.log('Saved successfully');
						} else {
							console.error('Failed to save file:', saveRes.errMsg);
						}
					} else {
						console.error('Failed to download image:', downloadRes.errMsg);
					}
				} catch (error) {
					console.error('Error downloading image:', error);
				}
			}
		},
		watch: {
			src: {
				handler() {
					// app端做图片缓存
					//#ifdef APP-PLUS
					this.getCacheImage().then(() => {
						if (!this.cacheImgUrl) {
							//没有缓存时候，就返回props.src
							this.cacheImgUrl = this.src;
							this.downloadAndCacheImage();
						}
					}).catch(() => {
						this.cacheImgUrl = this.src;
					})
					//#endif

					// 非app端直接返回props.src
					//#ifndef APP-PLUS
					this.cacheImgUrl = this.src;
					//#endif
				},
				immediate: true
			}
		},
		mounted() {
			if (process.env.NODE_ENV !== 'production') {
				if (!this.name) {
					console.warn("强烈建议！！！使用唯一name来做图片缓存key！！！！！")
				}
			}

		}
	};
</script>